home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / share / system-config-printer / authconn.py < prev    next >
Text File  |  2009-10-19  |  17KB  |  458 lines

  1. #!/usr/bin/env python
  2.  
  3. ## Copyright (C) 2007, 2008, 2009 Tim Waugh <twaugh@redhat.com>
  4. ## Copyright (C) 2007, 2008, 2009 Red Hat, Inc.
  5.  
  6. ## This program is free software; you can redistribute it and/or modify
  7. ## it under the terms of the GNU General Public License as published by
  8. ## the Free Software Foundation; either version 2 of the License, or
  9. ## (at your option) any later version.
  10.  
  11. ## This program is distributed in the hope that it will be useful,
  12. ## but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. ## GNU General Public License for more details.
  15.  
  16. ## You should have received a copy of the GNU General Public License
  17. ## along with this program; if not, write to the Free Software
  18. ## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  
  20. import threading
  21. import cups
  22. import cupspk
  23. import gobject
  24. import gtk
  25. import os
  26. from errordialogs import *
  27. from debug import *
  28.  
  29. _ = lambda x: x
  30. N_ = lambda x: x
  31. def set_gettext_function (fn):
  32.     global _
  33.     _ = fn
  34.  
  35. class AuthDialog(gtk.Dialog):
  36.     AUTH_FIELD={'username': N_("Username:"),
  37.                 'password': N_("Password:"),
  38.                 'domain': N_("Domain:")}
  39.  
  40.     def __init__ (self, title=None, parent=None,
  41.                   flags=gtk.DIALOG_MODAL | gtk.DIALOG_NO_SEPARATOR,
  42.                   buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
  43.                            gtk.STOCK_OK, gtk.RESPONSE_OK),
  44.                   auth_info_required=['username', 'password'],
  45.                   allow_remember=False):
  46.         if title == None:
  47.             title = _("Authentication")
  48.         gtk.Dialog.__init__ (self, title, parent, flags, buttons)
  49.         self.auth_info_required = auth_info_required
  50.         self.set_default_response (gtk.RESPONSE_OK)
  51.         self.set_border_width (6)
  52.         self.set_resizable (False)
  53.         hbox = gtk.HBox (False, 12)
  54.         hbox.set_border_width (6)
  55.         image = gtk.Image ()
  56.         image.set_from_stock (gtk.STOCK_DIALOG_AUTHENTICATION,
  57.                               gtk.ICON_SIZE_DIALOG)
  58.         image.set_alignment (0.0, 0.0)
  59.         hbox.pack_start (image, False, False, 0)
  60.         vbox = gtk.VBox (False, 12)
  61.         self.prompt_label = gtk.Label ()
  62.         vbox.pack_start (self.prompt_label, False, False, 0)
  63.  
  64.         num_fields = len (auth_info_required)
  65.         table = gtk.Table (num_fields, 2)
  66.         table.set_row_spacings (6)
  67.         table.set_col_spacings (6)
  68.  
  69.         self.field_entry = []
  70.         for i in range (num_fields):
  71.             field = auth_info_required[i]
  72.             label = gtk.Label (_(self.AUTH_FIELD.get (field, field)))
  73.             label.set_alignment (0, 0.5)
  74.             table.attach (label, 0, 1, i, i + 1)
  75.             entry = gtk.Entry ()
  76.             entry.set_visibility (field != 'password')
  77.             table.attach (entry, 1, 2, i, i + 1, 0, 0)
  78.             self.field_entry.append (entry)
  79.  
  80.         self.field_entry[num_fields - 1].set_activates_default (True)
  81.         vbox.pack_start (table, False, False, 0)
  82.         hbox.pack_start (vbox, False, False, 0)
  83.         self.vbox.pack_start (hbox)
  84.  
  85.         if allow_remember:
  86.             cb = gtk.CheckButton (_("Remember password"))
  87.             cb.set_active (False)
  88.             vbox.pack_start (cb)
  89.             self.remember_checkbox = cb
  90.  
  91.         self.vbox.show_all ()
  92.  
  93.     def set_prompt (self, prompt):
  94.         self.prompt_label.set_markup ('<span weight="bold" size="larger">' +
  95.                                       prompt + '</span>')
  96.         self.prompt_label.set_use_markup (True)
  97.         self.prompt_label.set_alignment (0, 0)
  98.         self.prompt_label.set_line_wrap (True)
  99.  
  100.     def set_auth_info (self, auth_info):
  101.         for i in range (len (self.field_entry)):
  102.             self.field_entry[i].set_text (auth_info[i])
  103.  
  104.     def get_auth_info (self):
  105.         return map (lambda x: x.get_text (), self.field_entry)
  106.  
  107.     def get_remember_password (self):
  108.         try:
  109.             return self.remember_checkbox.get_active ()
  110.         except AttributeError:
  111.             return False
  112.  
  113.     def field_grab_focus (self, field):
  114.         i = self.auth_info_required.index (field)
  115.         self.field_entry[i].grab_focus ()
  116.  
  117. class Connection:
  118.     def __init__ (self, parent=None, try_as_root=True, lock=False,
  119.                   host=None, port=None, encryption=None):
  120.         if host != None:
  121.             cups.setServer (host)
  122.         if port != None:
  123.             cups.setPort (port)
  124.         if encryption != None:
  125.             cups.setEncryption (encryption)
  126.  
  127.         self._use_password = ''
  128.         self._parent = parent
  129.         self._try_as_root = try_as_root
  130.         self._use_user = cups.getUser ()
  131.         self._server = cups.getServer ()
  132.         self._port = cups.getPort()
  133.         self._encryption = cups.getEncryption ()
  134.         self._prompt_allowed = True
  135.         self._operation_stack = []
  136.         self._lock = lock
  137.         self._gui_event = threading.Event ()
  138.         self._connect ()
  139.  
  140.     def _begin_operation (self, operation):
  141.         self._operation_stack.append (operation)
  142.  
  143.     def _end_operation (self):
  144.         self._operation_stack.pop ()
  145.  
  146.     def _get_prompt_allowed (self, ):
  147.         return self._prompt_allowed
  148.  
  149.     def _set_prompt_allowed (self, allowed):
  150.         self._prompt_allowed = allowed
  151.  
  152.     def _set_lock (self, whether):
  153.         self._lock = whether
  154.  
  155.     def _connect (self):
  156.         cups.setUser (self._use_user)
  157.  
  158.         self._use_pk = ((self._server[0] == '/' or self._server == 'localhost')
  159.                         and not self._lock
  160.                         and os.getuid () != 0)
  161.         if self._use_pk:
  162.             create_object = cupspk.Connection
  163.         else:
  164.             create_object = cups.Connection
  165.  
  166.         self._connection = create_object (host=self._server,
  167.                                             port=self._port,
  168.                                             encryption=self._encryption)
  169.  
  170.         if self._use_pk:
  171.             self._connection.set_parent(self._parent)
  172.  
  173.         self._user = self._use_user
  174.         debugprint ("Connected as user %s" % self._user)
  175.         methodtype_lambda = type (self._connection.getPrinters)
  176.         methodtype_real = type (self._connection.addPrinter)
  177.         for fname in dir (self._connection):
  178.             if fname[0] == '_':
  179.                 continue
  180.             fn = getattr (self._connection, fname)
  181.             if not type (fn) in [methodtype_lambda, methodtype_real]:
  182.                 continue
  183.             setattr (self, fname, self._make_binding (fname, fn))
  184.  
  185.     def _make_binding (self, fname, fn):
  186.         return lambda *args, **kwds: self._authloop (fname, fn, *args, **kwds)
  187.  
  188.     def _authloop (self, fname, fn, *args, **kwds):
  189.         self._passes = 0
  190.         c = self._connection
  191.         retry = False
  192.         while retry or self._perform_authentication () != 0:
  193.             if c != self._connection:
  194.                 # We have reconnected.
  195.                 fn = getattr (self._connection, fname)
  196.                 c = self._connection
  197.  
  198.             cups.setUser (self._use_user)
  199.  
  200.             try:
  201.                 result = fn.__call__ (*args, **kwds)
  202.  
  203.                 if fname == 'adminGetServerSettings':
  204.                     # Special case for a rubbish bit of API.
  205.                     if result == {}:
  206.                         # Authentication failed, but we aren't told that.
  207.                         raise cups.IPPError (cups.IPP_NOT_AUTHORIZED, '')
  208.                 break
  209.             except cups.IPPError, (e, m):
  210.                 if self._use_pk and m == 'pkcancel':
  211.                     title = _('Unauthorized request (%s)') % fname
  212.                     text = _("You are not authorized to carry out the "
  213.                              "requested action.")
  214.                     show_error_dialog (title, text, None)
  215.                     raise cups.IPPError (0, _("Operation canceled"))
  216.                 if not self._cancel and (e == cups.IPP_NOT_AUTHORIZED or
  217.                                          e == cups.IPP_FORBIDDEN):
  218.                     self._failed (e == cups.IPP_FORBIDDEN)
  219.                 elif not self._cancel and e == cups.IPP_SERVICE_UNAVAILABLE:
  220.                     if self._lock:
  221.                         self._gui_event.clear ()
  222.                         gobject.timeout_add (1, self._ask_retry_server_error, m)
  223.                         self._gui_event.wait ()
  224.                     else:
  225.                         self._ask_retry_server_error (m)
  226.  
  227.                     if self._retry_response == gtk.RESPONSE_OK:
  228.                         debugprint ("retrying operation...")
  229.                         retry = True
  230.                         self._passes -= 1
  231.                     else:
  232.                         self._cancel = True
  233.                         raise
  234.                 else:
  235.                     if self._cancel and not self._cannot_auth:
  236.                         raise cups.IPPError (0, _("Operation canceled"))
  237.  
  238.                     raise
  239.             except cups.HTTPError, (s,):
  240.                 if not self._cancel and (s == cups.HTTP_UNAUTHORIZED or
  241.                                          s == cups.HTTP_FORBIDDEN):
  242.                     self._failed (s == cups.HTTP_FORBIDDEN)
  243.                 else:
  244.                     raise
  245.  
  246.         return result
  247.  
  248.     def _ask_retry_server_error (self, message):
  249.         if self._lock:
  250.             gtk.gdk.threads_enter ()
  251.  
  252.         try:
  253.             msg = _("CUPS server error (%s)") % self._operation_stack[0]
  254.         except IndexError:
  255.             msg = _("CUPS server error")
  256.  
  257.         d = gtk.MessageDialog (self._parent,
  258.                                gtk.DIALOG_MODAL |
  259.                                gtk.DIALOG_DESTROY_WITH_PARENT,
  260.                                gtk.MESSAGE_ERROR,
  261.                                gtk.BUTTONS_NONE,
  262.                                msg)
  263.                                
  264.         d.format_secondary_text (_("There was an error during the "
  265.                                    "CUPS operation: '%s'." % message))
  266.         d.add_buttons (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
  267.                        _("Retry"), gtk.RESPONSE_OK)
  268.         d.set_default_response (gtk.RESPONSE_OK)
  269.         if self._lock:
  270.             d.connect ("response", self._on_retry_server_error_response)
  271.             gtk.gdk.threads_leave ()
  272.         else:
  273.             self._retry_response = d.run ()
  274.             d.destroy ()
  275.  
  276.     def _on_retry_server_error_response (self, dialog, response):
  277.         self._retry_response = response
  278.         dialog.destroy ()
  279.         self._gui_event.set ()
  280.  
  281.     def _failed (self, forbidden=False):
  282.         self._has_failed = True
  283.         self._forbidden = forbidden
  284.  
  285.     def _password_callback (self, prompt):
  286.         debugprint ("Got password callback")
  287.         if self._cancel or self._auth_called:
  288.             return ''
  289.  
  290.         self._auth_called = True
  291.         self._prompt = prompt
  292.         return self._use_password
  293.  
  294.     def _perform_authentication (self):
  295.         self._passes += 1
  296.  
  297.         debugprint ("Authentication pass: %d" % self._passes)
  298.         if self._passes == 1:
  299.             # Haven't yet tried the operation.  Set the password
  300.             # callback and return > 0 so we try it for the first time.
  301.             self._has_failed = False
  302.             self._forbidden = False
  303.             self._auth_called = False
  304.             self._cancel = False
  305.             self._cannot_auth = False
  306.             self._dialog_shown = False
  307.             cups.setPasswordCB (self._password_callback)
  308.             debugprint ("Authentication: password callback set")
  309.             return 1
  310.  
  311.         debugprint ("Forbidden: %s" % self._forbidden)
  312.         if not self._has_failed:
  313.             # Tried the operation and it worked.  Return 0 to signal to
  314.             # break out of the loop.
  315.             debugprint ("Authentication: Operation successful")
  316.             return 0
  317.  
  318.         # Reset failure flag.
  319.         self._has_failed = False
  320.  
  321.         if self._passes >= 2:
  322.             # Tried the operation without a password and it failed.
  323.             if (self._try_as_root and
  324.                 self._user != 'root' and
  325.                 (self._server[0] == '/' or self._forbidden)):
  326.                 # This is a UNIX domain socket connection so we should
  327.                 # not have needed a password (or it is not a UDS but
  328.                 # we got an HTTP_FORBIDDEN response), and so the
  329.                 # operation must not be something that the current
  330.                 # user is authorised to do.  They need to try as root,
  331.                 # and supply the password.  However, to get the right
  332.                 # prompt, we need to try as root but with no password
  333.                 # first.
  334.                 debugprint ("Authentication: Try as root")
  335.                 self._use_user = 'root'
  336.                 self._auth_called = False
  337.                 self._connect ()
  338.                 return 1
  339.  
  340.         if not self._prompt_allowed:
  341.             debugprint ("Authentication: prompting not allowed")
  342.             self._cancel = True
  343.             return 1
  344.  
  345.         if not self._auth_called:
  346.             # We aren't even getting a chance to supply credentials.
  347.             debugprint ("Authentication: giving up")
  348.             self._cancel = True
  349.             self._cannot_auth = True
  350.             return 1
  351.  
  352.         # Reset the flag indicating whether we were given an auth callback.
  353.         self._auth_called = False
  354.  
  355.         # If we're previously prompted, explain why we're prompting again.
  356.         if self._dialog_shown:
  357.             if self._lock:
  358.                 self._gui_event.clear ()
  359.                 gobject.timeout_add (1, self._show_not_authorized_dialog)
  360.                 self._gui_event.wait ()
  361.             else:
  362.                 self._show_not_authorized_dialog ()
  363.  
  364.         if self._lock:
  365.             self._gui_event.clear ()
  366.             gobject.timeout_add (1, self._perform_authentication_with_dialog)
  367.             self._gui_event.wait ()
  368.         else:
  369.             self._perform_authentication_with_dialog ()
  370.  
  371.         if self._cancel:
  372.             debugprint ("cancelled")
  373.             return -1
  374.  
  375.         cups.setUser (self._use_user)
  376.         debugprint ("Authentication: Reconnect")
  377.         self._connect ()
  378.         return 1
  379.  
  380.     def _show_not_authorized_dialog (self):
  381.         if self._lock:
  382.             gtk.gdk.threads_enter ()
  383.         d = gtk.MessageDialog (self._parent,
  384.                                gtk.DIALOG_MODAL |
  385.                                gtk.DIALOG_DESTROY_WITH_PARENT,
  386.                                gtk.MESSAGE_ERROR,
  387.                                gtk.BUTTONS_CLOSE)
  388.         d.set_title (_("Not authorized"))
  389.         d.set_markup ('<span weight="bold" size="larger">' +
  390.                       _("Not authorized") + '</span>\n\n' +
  391.                       _("The password may be incorrect."))
  392.         if self._lock:
  393.             d.connect ("response", self._on_not_authorized_dialog_response)
  394.             d.show_all ()
  395.             d.show_now ()
  396.             gtk.gdk.threads_leave ()
  397.         else:
  398.             d.run ()
  399.             d.destroy ()
  400.  
  401.     def _on_not_authorized_dialog_response (self, dialog, response):
  402.         self._gui_event.set ()
  403.         dialog.destroy ()
  404.  
  405.     def _perform_authentication_with_dialog (self):
  406.         if self._lock:
  407.             gtk.gdk.threads_enter ()
  408.  
  409.         # Prompt.
  410.         if len (self._operation_stack) > 0:
  411.             try:
  412.                 title = _("Authentication (%s)") % self._operation_stack[0]
  413.             except IndexError:
  414.                 title = _("Authentication")
  415.  
  416.             d = AuthDialog (title=title,
  417.                             parent=self._parent)
  418.         else:
  419.             d = AuthDialog (parent=self._parent)
  420.  
  421.         d.set_prompt (self._prompt)
  422.         d.set_auth_info ([self._use_user, ''])
  423.         d.field_grab_focus ('password')
  424.         d.set_keep_above (True)
  425.         d.show_all ()
  426.         d.show_now ()
  427.         self._dialog_shown = True
  428.         if self._lock:
  429.             d.connect ("response", self._on_authentication_response)
  430.             gtk.gdk.threads_leave ()
  431.         else:
  432.             response = d.run ()
  433.             self._on_authentication_response (d, response)
  434.  
  435.     def _on_authentication_response (self, dialog, response):
  436.         (self._use_user,
  437.          self._use_password) = dialog.get_auth_info ()
  438.         dialog.destroy ()
  439.  
  440.         if (response == gtk.RESPONSE_CANCEL or
  441.             response == gtk.RESPONSE_DELETE_EVENT):
  442.             self._cancel = True
  443.  
  444.         if self._lock:
  445.             self._gui_event.set ()
  446.  
  447. if __name__ == '__main__':
  448.     # Test it out.
  449.     gtk.gdk.threads_init ()
  450.     from timedops import TimedOperation
  451.     set_debugging (True)
  452.     c = TimedOperation (Connection, args=(None,)).run ()
  453.     debugprint ("Connected")
  454.     c._set_lock (True)
  455.     print TimedOperation (c.getFile,
  456.                           args=('/admin/conf/cupsd.conf',
  457.                                 '/dev/stdout')).run ()
  458.